package com.zareal.ymcc.exception;

import com.zareal.ymcc.enums.GlobalErrorCode;
import com.zareal.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
// 日志器注解
@Slf4j
public class GlobalExceptionHandler {

    // 捕捉全局
    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        if(e.getClass().getName().indexOf("AccessDeniedException") == -1 ){
            return JSONResult.error(GlobalErrorCode.USER_NO_PERMISSION_ERROR.toString());
        }
        e.printStackTrace();
        log.error("发生系统异常，异常信息为：{}",e.getMessage());
        return JSONResult.error(GlobalErrorCode.NOT.getErrorMessage());
    }

    // 全局业务异常GlobalCustomException
    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult globalExceptionHandler(GlobalCustomException e){
        e.printStackTrace();
        log.error("发生业务异常，异常码：{}, 异常信息：{}", e.getErrorCode(), e.getErrorMessage());
        return JSONResult.error(e);
    }

    // MethodArgumentNotValidException
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult globalExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error("发生业务异常,异常信息：{}", e.getMessage());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuffer buffer = new StringBuffer();
        allErrors.forEach(objectError -> buffer.append(objectError.getDefaultMessage()).append(";"));
        return JSONResult.error(buffer.toString());
    }
}
